#!/usr/local/bin/python2.6

# Copyright (c) 2010-, WangFei, Cloud Team, CGCL,
# All rights reserved.
# Test MPI ENVIRONMENT
import os, sys
import paramiko
import MySQLdb
import string
import time

def isDigtal(myNum):
    nums = string.digits
    if type(myNum) is not str:
        return False
    else:
        for temp in myNum:
            if temp not in nums:
                return False
        return True

def checkParameter(conn):
    global env_id
    if not conn:
        print "Can not connect to database, Fail!"
        return -1
    paraCnt=len(sys.argv)
    if paraCnt != 2:
        return 0
    env_id=str(sys.argv[1])
    if not isDigtal(job_id):
        return 0
    
    flag = conn.execute("select env_id from mpi_env where env_id = " + env_id);
    if flag == 0:
        print "No Job ", env_id
        return 0
    return 1

def test(master_address,user):
    command="ssh "+user+"@" + master_address + " \"mpdtrace -l\""
    os.popen(commmand)
    print out.read()
    client.close()

def getinfo(conn,job_id):
    global masterIP
    cnt = conn.execute("select vm_ip from env_resource, vm_info where env_id="+env_id+" and env_resource.vm_id=vm_info.vm_id and vm_info.vm_type='master_node'")
    if cnt != 1:
        print "Not Master Node,Fail!"
        return 0
    rows=conn.fetchall()
    masterIP=rows[0][0]

env_id="0"
masterIP="0"
tr_command="command format:\n" + \
"   mpitest env_id\n" + \
"   For example: mpitest 1"

if __name__ == "__main__":
    connect=MySQLdb.connect(host="localhost",port=3306,user="cloud",passwd="cloudpass",db="cloud")
    conn=connect.cursor()
    #print connect,conn
    flag = checkParameter(conn)
    if flag == -1:
        sys.exit(0)
    if flag == 0:
        print str_command
        sys.exit(0)
    
    getinfo(conn,env_id)
    test(masterIP,"root")      
    conn.close()
    connect.close()


